/*************************************************************************
	> File Name: fifo.c
	> Author: Angel Criss
	> Mail: abbytsing@gmail.com 
	> Created Time: 日  3/30 16:38:05 2014
 ************************************************************************/

#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>
int main(int argc, char *argv[])
{
    pid_t pid;
    char buf[14];
    if(argc<2)
    {
        printf("run by: ./a.out fialename\n");
        exit(0);
    }
    int fd;

    pid=fork();
    if(pid==0)
    {
        if((fd=open(argv[1],O_RDWR|O_NONBLOCK))>0)
        {
            int wr;
            if((wr=write(fd,"this is a test",14))>0)
            { printf("write to fifo succeded\n");
            _exit(0);
            }
        else
            {
                perror("write\n");
                exit(0);
            }
        }
        else
        {
            printf("can not open pipe\n");
            exit(0);
        }
    }
    else if(pid>0)
    {
        int rd;
        printf("read data in parent process\n");
        if((rd=read(fd,buf,14))>0)
        {
            printf("read from fifo succeded\nand now print it out\n:");
            int i;
            for(i=0;i<14;i++)
            {
                printf("%c",buf[i]);
            }
        }
        else
        {
            printf("cannot read from pipe\n");
            exit(0);
        }
    }
}
